package study.datastructure.queue.impl;/**
 * @program: datastructure
 * @author: lcy
 * @create: 2024-10-22 17:37
 */

import study.datastructure.queue.Queue;

import java.util.Iterator;

/**
 2024/10/22,
 */


public class ArrayQueue<E> implements Queue<E>, Iterable<E> {
    private E[] array; //环形数组实现
    private int head = 0;
    private int tail = 0;
    @SuppressWarnings("all") //抑制所有的警告
    public ArrayQueue(int capacity){
        array = (E[]) new Object[capacity+1]; //环形部分重合部分
    }

    @Override
    public Iterator<E> iterator() {
       return new Iterator<E>() {
           int p=head;
           @Override
           public boolean hasNext() {
               return p!=tail;
           }

           @Override
           public E next() {
               E e = array[p];
               p = (p+1)%array.length;
               return e;
           }
       };
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % array.length; //加到5 回到0
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E e = array[head];
        head = (head + 1) % array.length; //加到5 回到0
        return e;
    }

    @Override
    public E peek() {
        if (isEmpty()) return null;
        return array[head];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return (tail+1)%array.length == head; //环形数组，重合
    }

    public static void main(String[] args) {
        ArrayQueue<Integer> queue = new ArrayQueue<>(5);
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);
        queue.offer(5);
        queue.offer(6);
        for (Integer e : queue) {
            System.out.println(e);
        }
        System.out.println("queue poll= " + queue.poll());
        System.out.println("queue poll= " + queue.poll());
    }
}
